#! /bin/bash

set -e
set -x
work_dir=$(dirname $(dirname $(realpath $BASH_SOURCE)))

function main () {
  local readonly instance_id=$($work_dir/vultr/instance-create);
  local instance_ip=$($work_dir/vultr/wait-for-ip $instance_id);

  local gateway_ip=172.20.2.1;

  tar --exclude-vcs -czf /tmp/dev-env.tar.gz -C $(dirname $work_dir) dev-env

  scp -o "UserKnownHostsFile=/dev/null" \
      -o "StrictHostKeyChecking=no" \
      /tmp/dev-env.tar.gz \
      root@$instance_ip:/opt/dev-env.tar.gz

  function server_script () {
    local cmd=${1:?missing parameter cmd};

    ssh -o "UserKnownHostsFile=/dev/null" \
        -o "StrictHostKeyChecking=no" \
        root@$instance_ip $cmd
  }

  server_script "cd /opt && tar -xzf ./dev-env.tar.gz"


  scp -o "UserKnownHostsFile=/dev/null" \
      -o "StrictHostKeyChecking=no" \
      /tmp/dev-env.tar.gz \
      root@$gateway_ip:/opt/dev-env.tar.gz

  function gateway_script () {
    local cmd=${1:?missing parameter cmd};

    ssh -o "UserKnownHostsFile=/dev/null" \
        -o "StrictHostKeyChecking=no" \
        root@$gateway_ip $cmd
  }

  gateway_script "cd /opt && tar -xzf ./dev-env.tar.gz"


  gateway_script "systemctl stop wg-quick@wg0 || true";
  server_script "ufw disable || true";
  server_script "/opt/dev-env/vultr/apt-wait";

  local ss_password=$(openssl rand -base64 8);
  local ss_port=81;

  server_script "/opt/dev-env/shadowsocks/server-setup $ss_port $ss_password";
  gateway_script "/opt/dev-env/shadowsocks/client-setup $instance_ip $ss_port $ss_password 1080";


  local wg_server_private_key=$(wg genkey);
  local wg_server_public_key=$(echo $wg_server_private_key | wg pubkey);
  local wg_client_private_key=$(wg genkey);
  local wg_client_public_key=$(echo $wg_client_private_key | wg pubkey);
  local wg_port=51820;

  server_script "/opt/dev-env/wireguard/server-setup \
    \"$wg_server_private_key\" \
    \"$wg_client_public_key\" \
    $wg_port";
  gateway_script "/opt/dev-env/wireguard/gateway-setup \
    $instance_ip \
    \"$wg_server_public_key\" \
    \"$wg_client_private_key\" \
    $wg_port";

  echo;
  echo ss password: $ss_password;
  echo Instance Ip: $instance_ip;
}

main $@

